<!-- Main content -->
<section class="content">
    <div class="row">
        <div class="col-xs-12">

            <div class="box">
                <div class="box-header">
                    <h3 class="box-title">用户列表</h3>
                    <div class="margin">
                        <button type="button" id="add" class="btn btn-primary btn-sm"><i class="fa fa-plus"></i> 新增
                        </button>
                    </div>
                </div>
                <!-- /.box-header -->
                <div class="box-body">
                    <table id="userlist" class="table table-bordered table-striped">
                    </table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</section>
<!-- /.content -->
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog ">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span
                        class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">添加用户</h4>
            </div>
            <div class="modal-body">
                <form id="userForm" class="form-horizontal" action="<?php echo $this->url->get('user/add') ?>">
                    <input type="hidden" name="user_id" id="user_id" value="123">
                    <div class="box-body">
                        <div class="form-group">
                            <label for="account" class="col-sm-3 control-label">账号：</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" name="account" id="account" placeholder="帐号">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="password" class="col-sm-3 control-label">密码：</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" name="password" id="password"
                                       placeholder="密码">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="nick_name" class="col-sm-3 control-label">用户名称：</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" name="nick_name" id="nick_name"
                                       placeholder="用户名称">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="email" class="col-sm-3 control-label">用户邮箱：</label>
                            <div class="col-sm-9">
                                <input type="email" class="form-control" name="email" id="email" placeholder="用户邮箱">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="email" class="col-sm-3 control-label">用户头像：</label>
                            <div class="col-sm-9">
                                <div id="user_image_progress" class="col-sm-12"></div>
                                <div id="user_image_btn" class="col-sm-3">上传</div>
                                <input type="hidden" class="form-control" name="user_image" id="user_image_val" value="" placeholder="用户头像">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="phone" class="col-sm-3 control-label">手机号码：</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" name="phone" id="phone" placeholder="手机号码">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="active" class="col-sm-3 control-label">是否激活：</label>
                            <div class="col-sm-9">
                                <label>
                                    <input type="radio" name="active" id="active" class="flat-red" value="1" checked>激活
                                </label>
                                <label>
                                    <input type="radio" name="active" id="active" class="flat-red" value="0">禁用
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="role_id" class="col-sm-3 control-label">角色：</label>
                            <div class="col-sm-9">
                                <?php echo $this->tag->selectStatic(['role_it', $roleList, 'emptyText' => '请选择角色', 'style' => 'width: 100%;', 'class' => 'form-control select2']); ?>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" id="userAdd" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
<!-- page script -->
<script type="text/javascript">
    function user_imageCallback(response)
    {
        if(!$('#user_imagePreview').length){
            $('#user_image_btn').after('<div id="user_imagePreview" class="col-sm-9 thumbnail" style="margin: 0px;"><img></div>');
        }
        if($('#user_image_val').length){
           $('#user_image_val').val(response.url); 
        }
    }
</script>
<?php echo $this->tag->webuploader('user_image', 'images', 'qiniu'); ?>
<script>
    $(function () {
        //Initialize Select2 Elements
        $(".select2").select2();
        //Flat red color scheme for iCheck
        $('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
            checkboxClass: 'icheckbox_flat-green',
            radioClass: 'iradio_flat-green'
        });
        var table = $("#userlist").DataTable({
            "autoWidth": false,
            "language": {
                url: '//static.tudouyu.cn/datatables/language/zh-CN.json',
            },
            "ajax": {
                "url": "<?php echo $this->url->get('user/index'); ?>",
                "type": "POST",
            },
            fixedHeader: true,
            <?php if ($totalUserCount > 10000): ?>
            "serverSide": true,
            <?php endif ?>
            //列表表头字段
            "columns": [
                {"data": "user_id", "title": "用户ID", "orderable": true, "searchable": false,},
                {"data": "account", "title": "账号", "orderable": true, "searchable": true,},
                {"data": "nick_name", "title": "用户名称", "orderable": true, "searchable": true,},
                {"data": "email", "title": "用户邮箱", "orderable": true, "searchable": true,},
                {"data": "user_image", "title": "用户头像", "orderable": false, "searchable": false,},
                {"data": "active", "title": "是否激活", "orderable": false, "searchable": false,},
                {"data": "role_id", "title": "角色名称", "orderable": false, "searchable": false,},
                {"data": "create_at", "title": "注册时间", "orderable": true, "searchable": false,},
                {
                    "data": null, "title": "操作", "orderable": false, "searchable": false,
                    "createdCell": function (td, cellData, rowData, row, col) {
                        $(td).html('<button class="btn btn-primary btn-sm edit" user_id="' + rowData.user_id + '"><i class="fa fa-edit"></i> 更新</button>&nbsp;<button class="btn btn-danger btn-sm del" user_id="' + rowData.user_id + '"><i class="fa fa-trash"></i> 删除</button>');
                    }
                },
            ],
        });
        //删除
        $(document).on('click', '.del', function () {
            var user_id = $(this).attr('user_id');
            $.confirm({
                title: '删除用户',
                content: '确定删除此用户么？',
                buttons: {
                    confirm: {
                        text: '确定',
                        action: function () {
                            $.ajax({
                                type: "POST",
                                url: "<?php echo $this->url->get('user/del') ?>",
                                data: {
                                    'user_id': user_id,
                                },
                                dataType: 'json',
                                success: function (data) {
                                    if (data.code == 200) {
                                        $.alert({
                                            title: null,
                                            content: data.message,
                                            autoClose: 'ok|1000',
                                        });
                                        table.ajax.reload();
                                    } else {
                                        $.alert(data.message);
                                    }
                                }
                            });
                        },
                    },
                    cancel: {
                        text: '取消',
                        action: function () {

                        },
                    }
                }
            });
        })
        //添加
        $("#add").on('click', function () {
            $("#userForm")[0].reset();
            $("#user_id").val('');
            $("#userForm").data('bootstrapValidator').resetForm();
            $('#myModalLabel').html('添加用户');
            $('#user_imagePreview').remove();
            $('#user_image_val').val('');
            $('#myModal').modal({
                show: true,
                keyboard: false,
                backdrop: 'static'
            });
        });
        //编辑
        $(document).on('click', '.edit', function () {
            $("#userForm")[0].reset();
            $("#user_id").val('123');
            $("#userForm").data('bootstrapValidator').resetForm();
            $('#myModalLabel').html('编辑用户');
            if(!$('#user_imagePreview').length){
                //$('#user_image_btn').after('<div id="user_imagePreview" class="col-sm-9 thumbnail" style="margin: 0px;"><img></div>');
            }
            //$('#user_image_val').val('');
            $('#myModal').modal({
                show: true,
                keyboard: false,
                backdrop: 'static'
            });
        });
        //表单提交
        $("#userAdd").on('click', function () {
            $("#userForm").submit();
            table.ajax.reload();
        });
        $("#userForm").bootstrapValidator({
            excluded: ':disabled',
            message: 'This value is not valid',
            feedbackIcons: {
                /*input状态样式图片*/
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            submitHandler: function (validator, form, submitButton) {
                $.post(form.attr('action'), form.serialize(), function (result) {
                    // The result is a JSON formatted by your back-end
                    // I assume the format is as following:
                    //  {
                    //      valid: true,          // false if the account is not found
                    //      username: 'Username', // null if the account is not found
                    //  }
                    if (result.valid == true || result.valid == 'true') {
                        // You can reload the current location
                        window.location.reload();

                        // Or use Javascript to update your page, such as showing the account name
                        // $('#welcome').html('Hello ' + result.username);
                    } else {
                        // The account is not found
                        // Show the errors
                        $('#errors').html('The account is not found').removeClass('hide');

                        // Enable the submit buttons
                        $('#loginForm').bootstrapValidator('disableSubmitButtons', false);
                    }
                }, 'json');
            },
            fields: {
                account: {
                    message: '帐号无效',
                    validators: {
                        notEmpty: {
                            message: '帐号不能为空'
                        },
                        stringLength: {
                            min: 6,
                            max: 30,
                            message: '帐号长度必须在6到30之间',
                        },
                        threshold: 6, //有6字符以上才发送ajax请求，（input中输入一个字符，插件会向服务器发送一次，设置限制，6字符以上才开始）
                        remote: {//ajax验证。server result:{"valid",true or false} 向服务发送当前input name值，获得一个json数据。例表示正确：{"valid",true}
                            url: '<?php echo $this->url->get('user/checkAccount') ?>',//验证地址
                            message: '帐号已存在',//提示消息
                            delay: 2000,//每输入一个字符，就发ajax请求，服务器压力还是太大，设置2秒发送一次ajax（默认输入一个字符，提交一次，服务器压力太大）
                            type: 'POST',//请求方式
                            //自定义提交数据，默认值提交当前input value
                            data: function (validator) {
                                return {
                                    user_id: $('input[name="user_id"]').val(),
                                };
                            }
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9_\.]+$/,
                            message: '用户名由数字字母下划线和.组成'
                        }
                    }
                },
                password: {
                    message: '密码无效',
                    validators: {
                        /*notEmpty: {
                            message: '密码不能为空'
                        },*/
                        stringLength: {
                            min: 6,
                            max: 30,
                            message: '用户名长度必须在6到30之间'
                        },
                        identical: {//相同
                            field: 'password', //需要进行比较的input name值
                            message: '两次密码不一致'
                        },
                        different: {//不能和用户名相同
                            field: 'username',//需要进行比较的input name值
                            message: '不能和用户名相同'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9_\.]+$/,
                            message: 'The username can only consist of alphabetical, number, dot and underscore'
                        },
                        callback:{
                            message:'密码不能为空',
                            callback:function (value, validator) {
                                if ($('input[name="user_id"]').val() == ''){
                                    if (value == ''){
                                        return false;
                                    }else{
                                        return true;
                                    }
                                }else{
                                    return true;
                                }
                            }
                        }
                    }
                },
                nick_name: {
                    message: '用户名称无效',
                    validators: {
                        notEmpty: {
                            message: '用户名称不能为空'
                        },
                    }
                },
                email: {
                    validators: {
                        notEmpty: {
                            message: '邮件不能为空'
                        },
                        emailAddress: {
                            message: '请输入正确的邮件地址如：123@qq.com'
                        }
                    }
                },
                phone: {
                    message: '手机号码无效',
                    validators: {
                        notEmpty: {
                            message: '手机号码不能为空'
                        },
                        stringLength: {
                            min: 11,
                            max: 11,
                            message: '请输入11位手机号码'
                        },
                        regexp: {
                            regexp: /^1[3|5|8]{1}[0-9]{9}$/,
                            message: '请输入正确的手机号码'
                        }
                    }
                },
                role_id: {
                    message: '无效角色',
                    validators: {
                        notEmpty: {
                            message: '请选择用户角色'
                        },
                    }
                }
            }
        });
    });
</script>